package cn.itcast.strategy;

import com.dangdang.ddframe.job.lite.api.strategy.JobInstance;
import com.dangdang.ddframe.job.lite.api.strategy.JobShardingStrategy;

import java.util.*;

public class MyJobShardingStrategy implements JobShardingStrategy {
    @Override
    public Map<JobInstance, List<Integer>> sharding(List<JobInstance> jobInstances, String jobName, int shardingTotalCount) {
        if(jobInstances.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<JobInstance, List<Integer>> allMap = new HashMap<>();
        //1.生成总分片项列表
        List<Integer> allSharingItem = new ArrayList<>();
        for (int i = 0; i < shardingTotalCount; i++) {
            allSharingItem.add(i);
        }
        //2.迭代服务列表，获取每个服务，给每个服务指定分片项的集合。
        for (int i = 0; i < jobInstances.size(); i++) {
            JobInstance jobInstance = jobInstances.get(i);
            //计算服务对应分片项的集合
            List<Integer> sharingItem = getSharingItem(i, jobInstances.size(), allSharingItem);
            allMap.put(jobInstance,sharingItem);
        }
        return allMap;
    }

    private List<Integer> getSharingItem(int jobInstanceIndex,int size, List<Integer> allSharingItem) {
        List<Integer> sharingItem = new ArrayList<>();
        for (Integer item : allSharingItem) {
            if(item % size == jobInstanceIndex) {
                sharingItem.add(item);
            }
        }
        return sharingItem;
    }
}
